/*
Project home: https://code.google.com/p/jqeury-counter/

Licensing
The MIT License (MIT)

Copyright (c) 2013

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

//Mozilla animation fix
(function($) {
    if(!document.defaultView || !document.defaultView.getComputedStyle){
        var oldCSS = jQuery.css;
        jQuery.css = function(elem, name, force){
            if(name === 'background-position'){
                name = 'backgroundPosition';
            }
            if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
                return oldCSS.apply(this, arguments);
            }
            var style = elem.style;
            if ( !force && style && style[ name ] ){
                return style[ name ];
            }
            return oldCSS(elem, 'backgroundPositionX', force) +' '+ oldCSS(elem, 'backgroundPositionY', force);
        };
    }

    var oldAnim = $.fn.animate;
    $.fn.animate = function(prop){
        if('background-position' in prop){
            prop.backgroundPosition = prop['background-position'];
            delete prop['background-position'];
        }
        if('backgroundPosition' in prop){
            prop.backgroundPosition = '('+ prop.backgroundPosition + ')';
        }
        return oldAnim.apply(this, arguments);
    };

    function toArray(strg){
        strg = strg.replace(/left|top/g,'0px');
        strg = strg.replace(/right|bottom/g,'100%');
        strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
        var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
        return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
    }

    $.fx.step.backgroundPosition = function(fx) {
        if (!fx.bgPosReady) {
            var start = $.css(fx.elem,'backgroundPosition');

            if(!start){//FF2 no inline-style fallback
                start = '0px 0px';
            }

            start = toArray(start);

            fx.start = [start[0],start[2]];

            var end = toArray(fx.end);
            fx.end = [end[0],end[2]];

            fx.unit = [end[1],end[3]];
            fx.bgPosReady = true;
        }

        var nowPosX = [];
        nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
        nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
        fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];
    };
})(jQuery);

//counter plugin
(function( $ ){
    var properties = {
    };

    var methods = {
        getValue: function() {
            var $this = $(this);
            return $(this).eq(0).data('currentValue');
        },
        init : function( options ) {

            return this.each(function(){

                var $this = $(this);
                $this.data({digits: options["digits"]});

                var placeHolder = '';
                var digits = $this.data('digits');
                for (var i = digits-1; i >= 0 ; i--)
                {
                    placeHolder += '<div class="placeHolder_'+i+'"></div>'
                }
                $this.html('' +
                    '<div class="overlay"></div>' +
                    placeHolder
                );

                var separatorWidth = 1;
                var borderWidth = 3;
                var overlayWidth = digits*15+digits*separatorWidth-borderWidth;
                var counterWidth = digits*15+borderWidth+separatorWidth*(digits-1);
                $this.find('.overlay')
                    .css('width', overlayWidth+'px')
                    .css('height', '18px')
                    .css('background', 'url()')
                    .css('position', 'relative')
                    .css('zIndex', '20')
                    .css('border', '#cacaca solid '+borderWidth+'px')
                    .css('borderRadius', '5px');
                $this.find('[class^="placeHolder"]').each(function(i, e){
                    $(e).css('height', '18px')
                        .css('width', '15px')
                        .css('background', "url() 0px 1px")
                        .css('position', 'relative')
                        .css('top', '-21px')
                        .css('float', 'left')
                        .css('marginLeft', (i > 0 ? separatorWidth+'px' : 2*separatorWidth+'px'));
                });
                $this
                    .css('width', counterWidth+'px')
                    .css('margin', 'auto');
                $this.data({currentValue: 0});
                $this.data({animationRunning: false});
            });
        },
        destroy : function( ) {

            return this.each(function(){

                var $this = $(this);

                $(window).unbind('.counter');
                $this.removeData('counter');

            })

        },
        parseValue: function(value){
            return parseInt(value.split(' ')[1].split('px')[0]);
        },
        resetCounter: function(){
            var $this = $(this);
            if ($this.data('currentValue') != 0)
            {
                for (var i = 0; i<$this.data('digits'); i++)
                {
                    $this.find('[class=placeHolder_'+i+']').animate({
                        backgroundPosition: '0px 1px',
                        easing: 'linear'
                    }, {
                        duration:350,
                        complete: function(){
                            if ($(this).attr('class').substr(-1) == ($this.data('digits') - 1))
                            {
                                $this.trigger('continueEvent');
                            }
                        }
                    });
                }
            }
            return this;
        },
        setCounter: function(value){
            var returnObject = this.each(function(){
                var $this = $(this);
                if ($this.data('animationRunning'))
                {
                    return $this;
                }
                $this.data({animationRunning: true});

                var localValue = $this.data('currentValue');
                $this.data({currentValue: parseInt(value)});

                if (value.length > 0)
                {
                    var execute = function (value) {
                        var valArr = value.split('').reverse();
                        for (var i = 0; i<value.length; i++)
                        {
                            if (i == $this.data('digits'))
                            {
                                break;
                            }
                            var digit = valArr[i];
                            var direction = (Math.random() > 0.5 ? "+" : "-");
                            if ($.isNumeric(digit))
                            {
                                var newValue = methods.parseValue($this.find('[class="placeHolder_'+i+'"]').css('backgroundPosition'))+(direction === "+" ? 160 : -160);
                                $this.find('[class="placeHolder_'+i+'"]').animate({
                                    backgroundPosition: '0px ' + newValue + 'px',
                                    easing: 'linear'
                                }, 700, function(){
                                });
                                direction === '+' ? direction = '-' : direction = '+';
                                var position = 10-digit;
                                newValue = methods.parseValue($this.find('[class=placeHolder_'+i+']').css('backgroundPosition'))+(direction ? (parseInt(position)*16) : -(parseInt(position)*16));
                                $this.find('[class=placeHolder_'+i+']').animate({
                                    backgroundPosition: '0px '+newValue+'px',
                                    easing: 'linear'
                                },
                                {
                                    duration: digit*70,
                                    complete: function(){
                                        var bgndPos = methods.parseValue($(this).css('backgroundPosition'));
                                        if (bgndPos < -159)
                                        {
                                            while (bgndPos < -159)
                                            {
                                                bgndPos += 160;
                                                $(this).css('backgroundPosition', '0px '+bgndPos+'px');
                                            }
                                        }
                                        if (methods.parseValue($(this).css('backgroundPosition')) > 160)
                                        {
                                            while (bgndPos > 160)
                                            {
                                                bgndPos -= 160;
                                                $(this).css('backgroundPosition', '0px '+bgndPos+'px');
                                            }
                                        }
                                        
                                        if ($(this).attr('class').substr(-1) == (Math.min(value.length, $this.data('digits')) - 1))
                                        {
                                            var $that = $(this);
                                            $this.data({animationRunning: false});
                                        }
                                    }
                                });
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                }

                if ($.isNumeric((value)))
                {
                    if (localValue > 0)
                    {
                        $this.counter('resetCounter');

                        $this.bind('continueEvent', function(){
                            $this.unbind('continueEvent');
                            $this.data({currentValue: 0});
                            execute(value);
                        });
                        return;
                    }
                    else
                    {
                        $this.unbind('continueEvent');
                        execute(value);
                    }
                }
                else
                {
                    return;
                }
            });
            
            return returnObject;
        },
        addValue: function(value){
            var $this = $(this);

            var addValueFunction = function(){
                $this.each(function(){
                    $that = $(this);
                    var add = 0;
                    if (value.length > 0)
                    {
                        if ($.isNumeric((value)))
                        {
                            add = parseInt(value);
                        }
                        else
                        {
                            return this;
                        }
                    }

                    var valArr = value.split('').reverse();
                    var carry = false;
                    for (var i = 0; i<value.length; i++)
                    {
                        var digit = parseInt(valArr[i]) + (carry ? 1 : 0);

                        carry = digit + (parseInt($this.data('currentValue').toString().split('').reverse()[i])) > 9;

                        var newValue = methods.parseValue($this.find('[class="placeHolder_'+i+'"]').css('backgroundPosition'))-(digit*16)
                        $that.find('[class="placeHolder_'+i+'"]').animate({
                            backgroundPosition: '0px '+newValue+'px' ,
                            easing: 'linear'
                        }, digit*70, function(){
                            var bgndPos = methods.parseValue($(this).css('backgroundPosition'));
                            if (bgndPos < -159)
                            {
                                while (bgndPos < -159)
                                {
                                    bgndPos += 160;
                                    $(this).css('backgroundPosition', '0px '+bgndPos+'px');
                                }
                            }
                            if (methods.parseValue($(this).css('backgroundPosition')) > 160)
                            {
                                while (bgndPos > 160)
                                {
                                    bgndPos -= 160;
                                    $(this).css('backgroundPosition', '0px '+bgndPos+'px');
                                }
                            }
                        });
                    }

                    while (carry)
                    {
                        digit = 1;

                        carry = digit + (parseInt($this.data('currentValue').toString().split('').reverse()[i])) > 9;

                        $this.find('[class="placeHolder_'+i+'"]').animate({
                            backgroundPositionY: '-='+(digit*16),
                            easing: 'linear'
                        }, digit*70, function(){
                            var bgndPos = methods.parseValue($(this).css('backgroundPosition'));
                            if (bgndPos < -159)
                            {
                                while (bgndPos < -159)
                                {
                                    bgndPos += 160;
                                    $(this).css('backgroundPositionY', bgndPos+'px');
                                }
                            }
                            if (methods.parseValue($(this).css('backgroundPosition')) > 160)
                            {
                                while (bgndPos > 160)
                                {
                                    bgndPos -= 160;
                                    $(this).css('backgroundPositionY', bgndPos+'px');
                                }
                            }
                        });
                        i++;
                    }

                    var addedValue = $this.data('currentValue') + add;
                    $this.data({currentValue: addedValue});
                });
            };

            if ($this.data('animationRunning'))
            {
                $(this).unbind('addValueEvent');
                $(this).bind('addValueEvent', function(){ addValueFunction(); });
            }
            else
            {
                return addValueFunction();
            }

            return $(this);
        }
    };

    $.fn.counter = function( method ) {

        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.counter' );
        }

    };

})( jQuery );